<?php
// 算法控制器
namespace app\algorithm\controller;

use think\Controller;
use think\Db;
use think\Request;

class Algorithm
{


    /******************************* 计算某用户的累计业绩 START *******************************/
    // 查询出的用户id集合
    public $search_user_ids = [];
    /**
     * 获取某一个用户的所有下级用户id集合
     * @param int/array $in_user_id 用户id
     * @return array
     * */
    public function getSonUserIds($in_user_id)
    {
        if (is_array($in_user_id)) {
            $where['up_user_id'] = ['IN', $in_user_id];
        } else {
            $where['up_user_id'] = $in_user_id;
        }
        $user_id_list = Db::name('user')->field('id')->where($where)->select();

        $user_id_arr = array_column($user_id_list, 'id');
        if ($user_id_arr) {
            $this->search_user_ids = array_merge($this->search_user_ids, $user_id_arr);
            return $this->getSonUserIds($user_id_arr);
        } else {
            return $this->search_user_ids;
        }
    }

    // 调用示例
    public function getUser()
    {
        echo "<pre>";
        print_r($this->getSonUserIds(4));
        $this->search_user_ids = [];
        exit;
    }

    /**
     * 下级用户总累计业绩
     * @param int $user_id 用户id
     * @return float
     * */
    public function allConsume($user_id)
    {
        $son_user_ids = $this->getSonUserIds($user_id);
        if ($son_user_ids) {
            //['user_id' => $user_id, 'is_pay' => 1, 'back_order_sn' => '']
            $all_consume = Db::name('order')->where(['user_id' => ['IN', $son_user_ids], 'is_pay' => 1, 'complete_time' => ['neq', 0]])->sum('pay_price');
        } else {
            $all_consume = 0;
        }

        return sprintf('%.2f', $all_consume);
    }
    /******************************* 计算某用户的累计业绩 END *******************************/

    /**
     * 调用测试
     * */
    public function testFunctions()
    {
        $this->assign('title', '调用测试');
        return $this->view->fetch();
    }

}
